import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:developer';

import 'package:kasax_demos2/day14_stream/data_bloc.dart';

import 'data_bloc2.dart';

/// StreamBuilder 数据发生变化，会自动构建小部件
class StreamBuilderDemo3Home extends StatefulWidget {
  const StreamBuilderDemo3Home({Key? key}) : super(key: key);

  @override
  _StreamBuilderDemo3HomeState createState() => _StreamBuilderDemo3HomeState();
}

class _StreamBuilderDemo3HomeState extends State<StreamBuilderDemo3Home> {
  DataBloc2 _dataBloc = DataBloc2();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    _dataBloc.close();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("StreamBuilder3"),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FloatingActionButton(
            heroTag: "tag1",
            child: Text("add1"),
            onPressed: _addData2Stream,
          ),
          SizedBox(
            height: 10,
          ),
          FloatingActionButton(
            heroTag: "tag2",
            child: Text("add2"),
            onPressed: _addData2Stream2,
          ),
        ],
      ),
      body: Container(
        margin: EdgeInsets.only(left: 15, right: 15),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
              height: 15,
            ),
            Expanded(
                child: Container(
              child: SingleChildScrollView(
                child: Container(
                  child: StreamBuilder(
                    stream: _dataBloc.stream,
                    builder:
                        (BuildContext context, AsyncSnapshot<String> snapshot) {
                      print(
                          "${snapshot.connectionState} - ${snapshot.hasData} - ${snapshot.data}");
                      return Text(
                        "流数据: ${snapshot.data}",
                        style: Theme.of(context).textTheme.body1,
                      );
                    },
                  ),
                ),
              ),
            )),
            SizedBox(
              height: 15,
            ),
          ],
        ),
      ),
    );
  }

  _addData2Stream() {
    _dataBloc.add("test");
  }

  void _addData2Stream2() {
    _dataBloc.add("test2");
  }
}
